package com.tian.netty.executor;

import com.alibaba.fastjson.JSONObject;
import com.tian.entity.ChargeStationGun;
import com.tian.netty.core.ClientChannelMap;
import com.tian.netty.core.ReqDispatcher;
import com.tian.netty.core.RespDispatcher;
import com.tian.netty.message.AbstractMsg;
import com.tian.netty.message.MsgType;
import com.tian.netty.util.BCDUtil;
import com.tian.netty.util.EntityUtil;
import io.netty.channel.socket.SocketChannel;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.util.concurrent.Future;

/**
 * {@code @description:} TODO
 *
 * @author tianwc 公众号：Java后端技术全栈
 * 在线刷题 1200+java面试题和1000+篇技术文章：<a href="https://woaijava.cc/">博客地址</a>
 * {@code @date:} 2024-05-17 14:43
 * {@code @version:} 1.0
 */
@Slf4j
@Service
public class ChargingFlowServiceImpl implements ChargingFlowService {
    @Override
    public Future<Object> sendStarChargerMsg(JSONObject params) {
        SocketChannel channel = getSocketChannel(params.getString("chargerNo"));
        if (channel == null) {
            return null;
        }
        respStartMsg(channel, params);
        return RespDispatcher.submit(MsgType._0X_54, channel, params);
    }

    private SocketChannel getSocketChannel(String chargeNo) {
        ChargeStationGun charger = EntityUtil.getCharger(chargeNo);
        if (charger != null) {
            return ClientChannelMap.getSockeChannel(chargeNo);
        }
        return null;
    }

    public void respStartMsg(SocketChannel channel, JSONObject params) {
        final int LENGTH = 18;
        byte[] msgObject = new byte[LENGTH];
        int index = 0;
        msgObject[index++] = AbstractMsg.MSG_HEAD;
        msgObject[index++] = (byte) MsgType._0X_55;

        //充电桩编号
        byte[] chargerNoBytes = BCDUtil.str2Bcd(params.get("chargerNo").toString());
        for (int i = 0; i < 8 - chargerNoBytes.length; i++) {
            msgObject[index++] = AbstractMsg.FILLED_VAL;
        }

        for (byte b : chargerNoBytes) {
            msgObject[index++] = b;
        }

        //流水号
        byte[] orderBytes = BCDUtil.str2Bcd(params.get("orderId").toString());

        for (int i = 0; i < 8 - orderBytes.length; i++) {
            msgObject[index++] = AbstractMsg.FILLED_VAL;
        }

        for (byte b : orderBytes) {
            msgObject[index++] = b;
        }

        try {
            ReqDispatcher.submit(channel, msgObject);
        } catch (Exception e) {
            log.error("充电指令发送异常", e);
        }
    }
}
